<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.pescms.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\Admin;

use Core\Db\Db as Db;
use Model\Admin\UserModel as UserModel;
use Model\Admin\GroupModel as GroupModel;
use Model\Admin\NodeModel as NodeModel;
use Expand\Admin\Page as Page;

/**
 * Pes 会员管理模块
 * @author LazyPHP
 * @version 1.0
 */
class User extends Common {

    public function __construct() {
        parent::__construct();
    }

    /**
     * 用户列表
     */
    public function index() {
        $db = $this->db('user pu');
        $page = new Page;
        $total = count($db->join('pes_user_group pug on pug.id = pu.user_group_id')->select());
        $count = $page->total($total);
        $page->handle();
        $list = $db->join('pes_user_group pug on pug.id = pu.user_group_id')->limit("{$page->firstRow}, {$page->listRows}")->select();
        $show = $page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $group = GroupModel::getSelectGroup();
        $this->assign('group', $group);
        $this->display();
    }

    /**
     * 初始化添加用户
     */
    public function add() {
        $group = GroupModel::getSelectGroup();
        $this->assign('group', $group);
        $actionUrl = '/?g=Admin&m=User&a=insert';
        $this->assign('actionUrl', $actionUrl);
        $this->display();
    }

    /**
     * 添加用户
     */
    public function insert() {
        $data['user_group_id'] = $this->is_p('user_group_id', '请选择用户组');
        $data['account'] = $this->is_p('account', '请填写账号');
        $data['password'] = md5(md5($this->is_p('password', '请填写密码')));
        $data['mail'] = $this->is_p('mail', '请填写邮箱地址');
        $data['tel'] = $this->is_p('tel', '请填写手机号码');
        $data['nickname'] = $this->is_p('nickname', '请填写用户名');
        $data['status'] = $this->is_p('status', '请选择用户状态');
        $data['create_time'] = time();

        if (!filter_var($data['mail'], FILTER_VALIDATE_EMAIL)) {
            $this->error('请输入正确的电子邮箱');
        }

        $checkAccount = UserModel::getUser($data['account'], 'account');
        if ($checkAccount) {
            $this->error('账号已经存在！');
        }
        $checkMail = UserModel::getUser($data['mail'], 'mail');
        if ($checkMail) {
            $this->error('邮箱地址已经存在!');
        }

        $db = $this->db('user');
        $addUser = $db->add($data);

        $this->determineSqlExecResult($addUser, '添加用户失败!');

        $this->success('成功添加用户!', '/?g=Admin&m=User&a=index');
    }

    /**
     * 初始化编辑用户
     */
    public function edit() {
        $id = $this->is_g('id', '请选择要编辑的用户');
        $userInfo = UserModel::getUser($id);
        $this->determineSqlExecResult($userInfo, '用户不存在');
        foreach ($userInfo as $key => $value) {
            $this->assign($key, $value);
        }
        $group = GroupModel::getSelectGroup($userInfo['user_group_id']);
        $this->assign('group', $group);
        $actionUrl = '/?g=Admin&m=User&a=update&id=' . $id;
        $this->assign('actionUrl', $actionUrl);
        $this->display('User_add');
    }

    /**
     * 更新用户信息
     */
    public function update() {
        $id = $this->is_g('id', '请选择要编辑的用户');
        $checkUser = UserModel::getUser($id);
        $this->determineSqlExecResult($checkUser, '用户不存在');

        $data['user_group_id'] = $this->is_p('user_group_id', '请选择用户组');
        $data['account'] = $this->is_p('account', '请填写账号');
        if (!empty($_POST['password'])) {
            $data['password'] = md5(md5($_POST['password']));
        }
        $data['mail'] = $this->is_p('mail', '请填写邮箱地址');
        $data['tel'] = $this->is_p('tel', '请填写手机号码');
        $data['nickname'] = $this->is_p('nickname', '请填写用户名');
        $data['status'] = $this->is_p('status', '请选择用户状态');
        $data['create_time'] = time();

        if (!filter_var($data['mail'], FILTER_VALIDATE_EMAIL)) {
            $this->error('请输入正确的电子邮箱');
        }

        $checkAccount = UserModel::getUser($data['account'], 'account');
        if ($checkAccount['uid'] != $id) {
            $this->error('账号已经存在！');
        }

        $checkMail = UserModel::getUser($data['mail'], 'mail');
        if ($checkMail['uid'] != $id) {
            $this->error('邮箱地址已经存在!');
        }

        $db = $this->db('user');
        $updateResult = $db->where("uid = {$id}")->save($data);
        $this->determineSqlExecResult($updateResult, '更新用户失败');
        $this->success('成功更新用户信息!', '/?g=Admin&m=User&a=index');
    }

    /**
     * 删除用户
     */
    public function delete() {
        $id = $this->is_g('id', '请选择要编辑的用户');
        $checkUser = UserModel::getUser($id);
        $this->determineSqlExecResult($checkUser, '用户不存在');
        $db = $this->db('user');
        $deleteResult = $db->where("uid = {$id}")->delete();
        $this->determineSqlExecResult($deleteResult, '删除用户失败');
        $this->success('成功删除用户!', '/?g=Admin&m=User&a=index');
    }

    /**
     * 用户搜索
     */
    public function search() {
        $where = '';
        $data = '';

        if (empty($_POST['clear'])) {
            $data = $_SESSION['page']['data'];
            $where = $_SESSION['page']['where'];
        }

        $user_group_id = $this->p('user_group_id');
        if ($user_group_id > 0) {
            $data['user_group_id'] = $user_group_id;
            $where = 'pu.user_group_id = :user_group_id';
            $group = GroupModel::getSelectGroup($user_group_id);
            $this->assign('group', $group);
        } else {
            $group = GroupModel::getSelectGroup();
            $this->assign('group', $group);
        }
        $uid = $this->p('uid');
        if (!empty($uid)) {
            $data['uid'] = $uid;
            $where .= empty($where) ? 'pu.uid = :uid' : ' and pu.uid = :uid';
            $this->assign('uid', $uid);
        }
        $nickname = $this->p('nickname');
        if (!empty($nickname)) {
            $data['nickname'] = "%{$nickname}%";
            $where .= empty($where) ? 'pu.nickname like :nickname' : ' and pu.nickname like :nickname';
            $this->assign('nickname', $nickname);
        }

        $db = $this->db('user pu');
        $page = new Page;
        $total = count($db->join('pes_user_group pug on pug.id = pu.user_group_id')->where($where)->select($data));
        $count = $page->total($total);
        $page->handle();
        $list = $db->join('pes_user_group pug on pug.id = pu.user_group_id')->where($where)->limit("{$page->firstRow}, {$page->listRows}")->select($data);

        $show = $page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);

        //记录POST提交的数据
        $_SESSION['page']['data'] = $data;
        $_SESSION['page']['where'] = $where;
        $this->display('User_index');
    }

    /**
     * 节点列表
     */
    public function node() {
        $allNode = NodeModel::getNode();
        $list = NodeModel::getListNode($allNode, $allNode);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 添加节点
     */
    public function addNode() {
        if (!empty($_GET['pid'])) {
            $node = NodeModel::getSelectNode((int) $_GET['pid']);
        } else {
            $node = NodeModel::getSelectNode();
        }

        $this->assign('node', $node);
        $actionUrl = '/?g=Admin&m=User&a=insertNode';
        $this->assign('actionUrl', $actionUrl);
        $this->display();
    }

    /**
     * 插入节点
     */
    public function insertNode() {
        $data['pid'] = is_numeric($_POST['pid']) ? $_POST['pid'] : '请选择节点';
        $data['name'] = $this->is_p('name', '请填写节点名称');
        $data['title'] = $this->is_p('title', '请填写节点描述');
        $data['mes'] = $this->p('mes') ? $this->p('mes') : '您没有权限访问';
        $data['verify'] = is_numeric($_POST['verify']) && ($_POST['verify'] == 1 || $_POST['verify'] == 0) ? $_POST['verify'] : '请选择节点是否验证';
        $data['listsort'] = $this->p('listsort');

        $db = $this->db('node');
        $addResult = $db->add($data);
        $this->determineSqlExecResult($addResult, '添加节点失败');

        $this->setChild();
        $this->success('成功添加节点', '/?g=Admin&m=User&a=node');
    }

    /**
     * 编辑节点
     */
    public function editNode() {
        $id = $this->is_g('id', '请选择要编辑的节点');
        $list = NodeModel::getNode($id);
        $this->determineSqlExecResult($list, '不存在此节点');
        foreach ($list as $key => $value) {
            $this->assign($key, $value);
        }
        $node = NodeModel::getSelectNode($list['pid']);
        $this->assign('node', $node);
        $actionUrl = "/?g=Admin&m=User&a=updateNode&id={$id}";
        $this->assign('actionUrl', $actionUrl);
        $this->display('User_addNode');
    }

    /**
     * 更新节点
     */
    public function updateNode() {
        $data['id'] = $this->is_g('id', '请选择要编辑的节点');
        $list = NodeModel::getNode($data['id']);
        $this->determineSqlExecResult($list, '不存在此节点');
        $data['pid'] = is_numeric($_POST['pid']) ? $_POST['pid'] : '请选择节点';
        $data['name'] = $this->is_p('name', '请填写节点名称');
        $data['title'] = $this->is_p('title', '请填写节点描述');
        $data['mes'] = $this->p('mes') ? $this->p('mes') : '您没有权限访问';
        $data['verify'] = is_numeric($_POST['verify']) && ($_POST['verify'] == 1 || $_POST['verify'] == 0) ? $_POST['verify'] : '请选择节点是否验证';
        $data['listsort'] = $this->p('listsort');

        $db = $this->db('node');
        $updateResult = $db->where('id = :id')->save($data);
        $this->determineSqlExecResult($updateResult, '更新节点失败');
        $this->setChild();
        $this->success('成功更新节点', '/?g=Admin&m=User&a=node');
    }

    /**
     * 删除节点
     */
    public function deleteNode() {
        $data['id'] = $this->is_g('id', '请选择要编辑的节点');
        $list = NodeModel::getNode($data['id']);
        $this->determineSqlExecResult($list, '不存在此节点');
        $db = $this->db('node');
        $deleteResult = $db->where('id =:id')->delete($data);
        $this->determineSqlExecResult($deleteResult, '删除节点失败');
        $this->success('成功删除节点', '/?g=Admin&m=User&a=node');
    }

    /**
     * 添加子类
     */
    private function setChild() {
        $db = $this->db('node');
        $topCat = $db->where('pid = 0')->select();
        foreach ($topCat as $key => $value) {
            $child = NodeModel::listChildId($value['id']);
            NodeModel::$tree = '';
            $updateChild = $db->where('id = :id')->save(array('id' => $value['id'], 'child' => $child));
        }
    }

    /**
     * 用户组列表
     */
    public function group() {
        $db = $this->db('user_group');
        $page = new Page;
        $total = count($db->select());
        $count = $page->total($total);
        $page->handle();
        $list = $db->limit("{$page->firstRow}, {$page->listRows}")->select();
        $show = $page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 添加用户组
     */
    public function addGroup() {
        $actionUrl = '/?g=Admin&m=User&a=insertGroup';
        $this->assign('actionUrl', $actionUrl);
        $this->display();
    }

    /**
     * 插入用户组
     */
    public function insertGroup() {
        $data['name'] = $this->is_p('name', '请填写用户组名称');
        $existGroupName = GroupModel::getGroup($data['name'], 'name');
        if (!empty($existGroupName)) {
            $this->error('用户组名已存在');
        }
        $data['createtime'] = time();
        $db = $this->db('user_group');
        $addResult = $db->add($data);
        $this->determineSqlExecResult($addResult, '添加用户组失败');

        $this->success('添加用户组成功!', '/?g=Admin&m=User&a=group');
    }

    /**
     * 编辑用户组
     */
    public function editGroup() {
        $id = $this->is_g('id', '请选择您要编辑的用户组');
        $checkGroup = GroupModel::getGroup($id);
        $this->determineSqlExecResult($checkGroup, '用户组不存在');
        foreach ($checkGroup as $key => $value) {
            $this->assign($key, $value);
        }
        $actionUrl = '/?g=Admin&m=User&a=updateGroup&id=' . $id;
        $this->assign('actionUrl', $actionUrl);
        $this->display('User_addGroup');
    }

    /**
     * 更新用户组
     */
    public function updateGroup() {
        $id = $this->is_g('id', '请选择您要编辑的用户组');
        $checkGroup = GroupModel::getGroup($id);
        $this->determineSqlExecResult($checkGroup, '用户组不存在');
        $data['id'] = $id;
        $data['name'] = $this->is_p('name', '请填写用户组名称');
        $db = $this->db('user_group');
        $updateResult = $db->where('id =:id')->save($data);
        $this->determineSqlExecResult($updateResult, '更新用户组失败');
        $this->success('更新用户组成功!', '/?g=Admin&m=User&a=group');
    }

    /**
     * 删除用户组
     */
    public function deleteGroup() {
        $id = $this->is_g('id', '请选择您要删除的用户组');
        $checkGroup = GroupModel::getGroup($id);
        $this->determineSqlExecResult($checkGroup, '用户组不存在');
        $data['id'] = $id;
        $db = $this->db('user_group');

        $deleteResult = $db->where("id = :id")->delete($data);
        $this->determineSqlExecResult($deleteResult, '删除用户组失败!');
        $this->success('成功删除用户组', '/?g=Admin&m=User&a=group');
    }

    /**
     * 初始化编辑权限
     */
    public function competence() {
        $id = $this->is_g('id', '请选择您要编辑权限的用户组');
        $checkGroup = GroupModel::getGroup($id);
        $this->determineSqlExecResult($checkGroup, '用户组不存在');
        $this->assign('competence', $checkGroup['competence']);
        //输出节点
        $allNode = NodeModel::getNode();
        $list = NodeModel::getListNode($allNode, $allNode);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 更新用户组权限
     */
    public function updateCompetence() {
        $data['id'] = $this->is_g('id', '请选择您要编辑权限的用户组');
        $checkGroup = GroupModel::getGroup($data['id']);
        $this->determineSqlExecResult($checkGroup, '用户组不存在');

        $data['competence'] = implode(',', (array) $_POST['competence']);

        $db = $this->db('user_group');
        $updateResult = $db->where('id =:id')->save($data);
        $this->determineSqlExecResult($updateResult, '更新用户组权限失败');
        $this->success('更新用户组权限成功', '/?g=Admin&m=User&a=group');
    }

}